import { useSelector, useDispatch } from "react-redux";
import { Button } from "antd";
import { EditTwoTone, DeleteTwoTone } from "@ant-design/icons";
import "./index.css";
import { useState } from "react";
import { postAdded, postUpdated, postDeleted } from "./postsSlice";
import { nanoid } from "@reduxjs/toolkit";
import FormAdd from "./FormAdd";
import { Link } from "react-router-dom";
export default function PostList() {
  const posts = useSelector((state) => state.posts);
  const dispatch = useDispatch();
  const [isModalOpen, setIsModalOpen] = useState(false);
  const [info, setInfo] = useState({});
  const [title, setTitle] = useState("添加文章");
  const handleCancel = () => {
    setIsModalOpen(false);
  };
  const handleAddArticle = () => {
    setInfo({});
    setTitle("添加文章");
    setIsModalOpen(true);
  };
  const onCreate = (values) => {
    console.log("dss", values);
    if (title === "添加文章") {
      dispatch(
        postAdded({
          id: nanoid(),
          title: values.title,
          content: values.content,
        })
      );
    }
    if (title === "编辑文章") {
      dispatch(
        postUpdated({
          id: info.id,
          title: values.title,
          content: values.content,
        })
      );
    }

    setIsModalOpen(false);
  };
  const onEditInfo = (item) => {
    setTitle("编辑文章");
    setInfo(item);
    setIsModalOpen(true);
  };
  const onDelInfo = (item) => {
    dispatch(
      postDeleted({
        id: item.id,
      })
    );
  };
  const renderedPosts = posts.map((post) => (
    <article className="post-excerpt" key={post.id}>
      <Button
        onClick={() => onEditInfo(post)}
        style={{ marginRight: "10px" }}
        type="primary"
        shape="circle"
        icon={<EditTwoTone />}
      />
      <Button
        onClick={() => onDelInfo(post)}
        type="primary"
        shape="circle"
        icon={<DeleteTwoTone />}
      />
      <h3>{post.title}</h3>
      <p className="post-content">{post.content.substring(0, 100)}</p>
      <Link to={`/post/${post.id}`}>view post</Link>
    </article>
  ));
  const NotFound = () => {
    return (
        <>
        <div>暂无数据</div>
        </>
    )
  }
  return (
    <>
      <div>
        <Button onClick={handleAddArticle} type="primary">
          添加文章
        </Button>
      </div>
      <FormAdd
        info={info}
        onCreate={onCreate}
        isOpen={isModalOpen}
        handleCancel={handleCancel}
        title={title}
      ></FormAdd>
      <div className="post-list">
        <h2>posts</h2>
        {posts.length===0 && <NotFound/>}
        {posts.length>0 && renderedPosts}
      </div>
    </>
  );
}
